package com.echo.utils;

import com.echo.entity.WisUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtils {
    /**
     * 构建token的主题
     */
    private static final String SUBJECT = "echo_exam";
    /**
     * 过期时间为1天
     */
    private static final long EXPIRE = 1000 * 60 * 60 * 24;

    // Change this to use a proper secure key with a size of at least 256 bits
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    /**
     * 生成JWT Token
     */
    public static String genJsonWebToken(WisUser wisUser) {
        if (wisUser == null || wisUser.getUserId() == null || wisUser.getUserUsername() == null || wisUser.getUserAvatar() == null) {
            return null;
        }
        return Jwts.builder()
                .setSubject(SUBJECT)
                // 下面3行设置token中间字段，携带用户的信息
                .claim("id", wisUser.getUserId())
                .claim("username", wisUser.getUserUsername())
                .claim("avatar", wisUser.getUserAvatar())
                .setIssuedAt(new Date())
                // 设置过期时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SECRET_KEY)
                // 生成的结果字符串太长，这里压缩下
                .compact();
    }

    /**
     * 校验token
     *
     * @param token 生成的token
     * @return 解析出的Claims信息
     */
    public static Claims checkJWT(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            // 篡改token会导致校验失败，走到异常分支，这里返回null
            return null;
        }
    }
}
